import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {HttpService} from '../../../service/http.service';
import {NavController} from '@ionic/angular';
import {AlertController} from '@ionic/angular';
import {PickerController} from '@ionic/angular';
import {ModalController} from '@ionic/angular';
import {RegionPickModelComponent} from '../../../components/region-pick-model/region-pick-model.component';
import {ToastService} from '../../../service/toast.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'app-doctor-register',
    templateUrl: './doctor-register.page.html',
    styleUrls: ['./doctor-register.page.scss'],
})
export class DoctorRegisterPage implements OnInit {

    constructor(
        private router: Router,
        private navCtrl: NavController,
        private httpService: HttpService,
        private toastSrv: ToastService,
        public alertController: AlertController,
        public pickerController: PickerController,
        public modalController: ModalController,
        private translate: TranslateService,
    ) {
    }

    isShow = false;
    phoneNum = '';
    password = '';
    confirm = '';
    emailNum = '';
    emailCode = '';
    ifGetCode = false;
    countDown = 60;
    aTimer = null;

    aRegion = '';
    aRegionId = 0;
    aDepartment = '';
    aDepartmentId = 0;
    defaultColumnOptions = [];
    sysLang = '';
    verifyCode: any = {
        verifyCodeTips: 'GetCode',
        countdown: 300,
        disable: true,
    };

    ngOnInit() {
        this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
    }

    ionViewDidEnter() {
        this.getDepartments();
    }

    public async registerIme() {
        if (this.sysLang === 'en-us') {
            if (!this.emailNum) {
                this.toastSrv.showToast('Please Enter Email');
                return;
            }
            if (!this.emailCode) {
                this.toastSrv.showToast('Please Enter Verification Code');
                return;
            }
            if (!this.password || this.password.length < 8) {
                this.toastSrv.showToast('Password Must Be At Least 8 Characters');
                return;
            }
            if (!this.confirm || this.confirm.length < 8) {
                this.toastSrv.showToast('Please Enter Confirm Password');
                return;
            } else {
                if (this.password !== this.confirm) {
                    this.toastSrv.showToast('The Two Passwords You Typed Do Not Match');
                    return;
                }
            }
            if (!this.phoneNum) {
                this.toastSrv.showToast('Please Enter Exact Phone Number');
                return;
            }
        } else {
            if (!this.emailNum) {
                this.toastSrv.showToast('请输入邮箱号');
                return;
            }
            if (!this.emailCode) {
                this.toastSrv.showToast('请输入验证码');
                return;
            }
            if (!this.password || this.password.length < 8) {
                this.toastSrv.showToast('请输入至少8位密码');
                return;
            }
            if (!this.confirm || this.confirm.length < 8) {
                this.toastSrv.showToast('请输入确认密码');
                return;
            } else {
                if (this.password !== this.confirm) {
                    this.toastSrv.showToast('两次密码输入不一致');
                    return;
                }
            }
            if (!this.phoneNum) {
                this.toastSrv.showToast('请输入正确手机号');
                return;
            }
        }
        const result: any = await this.httpService.post()
            .setPath('/pub/user/doctorRegister')
            .setBody({
                email: this.emailNum,
                verifyCode: this.emailCode,
                password: this.password,
                confirm: this.confirm,
                region_id: this.aRegionId,
                department_id: this.aDepartmentId,
                phone: this.phoneNum
            })
            .request();
        if (result.status === 0) {
            // this.isShow = true;
            await this.toDoctorLogin();
        }
    }

    public async toDoctorLogin() {
        // this.isShow = false;
        // this.router.navigateByUrl('/doctor-login');
        // this.navCtrl.navigateForward('/doctor-login');

        const result: any = await this.httpService.post()
            .setPath('/pub/user/userLogin')
            .setBody({
                email: this.emailNum,
                password: this.password,
                userType: 2
            })
            .request();

        if (result.status === 0) {
            const loginInfo = result.data;
            localStorage.setItem('userId', loginInfo.userId);
            localStorage.setItem('userType', loginInfo.type);
            localStorage.setItem('auth-token', loginInfo.authToken);
            localStorage.setItem('redirectTo', '/doctor-app');
            await this.navCtrl.navigateRoot('/doctor-app');
        }
    }

    public async getCode() {
        if (this.sysLang === 'en-us') {
            if (!this.emailNum) {
                this.toastSrv.showToast('Please Enter Email');
                return;
            }
        } else {
            if (!this.emailNum) {
                this.toastSrv.showToast('请输入邮箱号');
                return;
            }
        }
        const result: any = await this.httpService.post()
            .setPath('/pub/user/verifyCode')
            .setBody({
                smsType: 1,
                type: 2,
                email: this.emailNum,
            })
            .request();
        if (result.status === 0) {
            if (this.sysLang === 'en-us') {
                const aWord = 'Message Sent';
                this.toastSrv.setDuration(5000).showToast(aWord);
            } else {
                const aWord = '验证码已发送';
                this.toastSrv.setDuration(5000).showToast(aWord);
            }
            if (result.data.expire < 300) {
            } else {
                this.verifyCode.disable = false;
                this.settime();
            }
        }
    }
    public settime() {
        if (this.verifyCode.countdown === 1) {
            this.verifyCode.countdown = 300;
            this.verifyCode.verifyCodeTips = 'GetCode';
            this.verifyCode.disable = true;
            return;
        } else {
            this.verifyCode.countdown--;
        }

        this.verifyCode.verifyCodeTips = (this.sysLang === 'en-us' ? 'Resend(' : '重新获取(') + this.verifyCode.countdown + ')';
        setTimeout(() => {
            this.verifyCode.verifyCodeTips = (this.sysLang === 'en-us' ? 'Resend(' : '重新获取(') + this.verifyCode.countdown + ')';
            this.settime();
        }, 1000);
    }

    public async selectRegion() {
        const result: any = await this.httpService.get()
            .setPath('/pub/source/threeRegionData')
            .setQuery({
                style: 'tree'
            })
            .request();

        if (result.status === 0) {
            const modal = await this.modalController.create({
                component: RegionPickModelComponent,
                componentProps: {
                    title: 'District Choose',
                    itemArray: [
                        {
                            name: 'Country Choose',
                            type: 1,
                        },
                        {
                            name: 'State Choose',
                            type: 2,
                        },
                        {
                            name: 'City Choose',
                            type: 3
                        },
                    ],
                    dataArray: [...result.data]
                }
            });
            await modal.present();
            const {data} = await modal.onDidDismiss();
            if (!!data) {
                this.aRegion = data[2].label;
                this.aRegionId = data[2].value;
            }
        }
    }

    public async openPicker(numColumns = 1, numOptions = 5, multiColumnOptions) {
        console.log(multiColumnOptions);
        const picker = await this.pickerController.create({
            columns: this.getColumns(numColumns, numOptions, multiColumnOptions),
            buttons: [
                {
                    text: 'Cancel',
                    role: 'cancel'
                },
                {
                    text: 'Confirm',
                    handler: (value) => {
                        this.aDepartment = value['col-0'].text;
                        this.aDepartmentId = value['col-0'].value;
                    }
                }
            ]
        });
        await picker.present();
    }

    private getColumns(numColumns, numOptions, columnOptions) {
        const columns = [];
        for (let i = 0; i < numColumns; i++) {
            columns.push({
                name: `col-${i}`,
                options: this.getColumnOptions(i, numOptions, columnOptions)
            });
        }
        return columns;
    }

    private getColumnOptions(columnIndex, numOptions, columnOptions) {
        const options = [];
        for (let i = 0; i < numOptions; i++) {
            options.push({
                text: columnOptions[columnIndex][i % numOptions].name,
                value: i
            });
        }
        return options;
    }

    private async getDepartments() {
        const result: any = await this.httpService.get().setPath('/pub/source/departmentList').request();
        if (result.status === 0) {
          this.defaultColumnOptions[0] = result.data;
        }
    }

    public goBack() {
        this.navCtrl.pop();
    }

    public toPrivacy() {
        this.navCtrl.navigateForward(['privacy']);
    }
}
